package com.youyun56.commons;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSAManager {
    private static KeyPair keyPair;

    // static {
    // keyPair = getKeyPair();
    // }
    private final static String UTF_8 = "UTF-8";

    public RSAManager(String rsakeyPath) {
        keyPair = getKeyPair(rsakeyPath);
    }

    public KeyPair getKeyPair(String rsakeyPath) {
        try {
            // 产生新密钥对
            // InputStream is = FileUtils.class.getResourceAsStream(rsakeyPath);
            InputStream is = new FileInputStream(new File(rsakeyPath));
            ObjectInputStream oos = new ObjectInputStream(is);
            KeyPair kp = (KeyPair) oos.readObject();
            oos.close();
            return kp;
        } catch (Exception e) {
            throw new SecurityException("couldn't get the key pair");
        }
    }

    public static void saveRSAKey(String path) throws NoSuchAlgorithmException, IOException {
        SecureRandom sr = new SecureRandom();
        KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
        // 注意密钥大小�?���?024,否则解密会有乱码情况.
        kg.initialize(1024, sr);
        FileOutputStream fos = new FileOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        // 生成密钥
        oos.writeObject(kg.generateKeyPair());
        oos.close();
    }

    public String encrypt(String unencryptedString) {
        if (unencryptedString == null || unencryptedString.trim().length() == 0) {
            throw new IllegalArgumentException("unencrypted string was null or empty");
        }

        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
            byte[] cleartext = unencryptedString.getBytes(UTF_8);
            byte[] ciphertext = cipher.doFinal(cleartext);

            return new String(Base64.encodeBase64(ciphertext), UTF_8);
        } catch (Exception e) {
            throw new SecurityException(e);
        }
    }

    public String decrypt(String encryptedString) {
        if (encryptedString == null || encryptedString.trim().length() <= 0) {
            throw new IllegalArgumentException("encrypted string was null or empty");
        }
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            byte[] cleartext = Base64.decodeBase64(encryptedString.getBytes(UTF_8));
            byte[] ciphertext = cipher.doFinal(cleartext);
            return new String(ciphertext, UTF_8);
        } catch (Exception e) {
            throw new SecurityException(e);
        }
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
        // RSAManager.saveRSAKey("oid");
        RSAManager rsaManager = new RSAManager(PathConfig.CONF_FOLDER + File.separator + "oid");
        System.out.println(rsaManager.encrypt("kingsley"));
        // System.out.println(RSAManager.encrypt("yilin"));
        // System.out
        // .println(RSAManager
        // .decrypt("YWwdBORyQaTuSzNBK4MSfqItxlDdNOF31RKo58pDnM5ebH2eLH37Yv3cTBA2xJ/zI3S0aHyeLROPpfly3SfDSHEwQpwU9pPX4toVtoe6GGtFZvuMYRBdyVZbwZeixQ2PyGs7Wftk0YfilprpInDo/KaPKiE/yXGpfPLCEUT2E30="));
        // System.out
        // .println(RSAManager
        // .decrypt("S8CYwBM/ifbFJkrmMhrO+ObZUT1xqKrjl1ItAgmmiNxDmZH/2QTPfcDtZcyS3nAXdUk5yHMRVzoMTwVunbLfPtZdGcnRtUxcqcOxlkK82JUnst12Nq5fJ0pBpJuY7grbvKWGacOn0GrzMht7EwUSi59jY33RyfYtKJfVGMwvRkg="));
    }
}
